using System;
using System.Text;
using System.Collections;

namespace MushManager.DAL
{
	
	internal enum QueryType { Insert, Update };

	internal struct QueryItem
	{
		public object value;
		public string name;

		public string GetSafeValue()
		{
			if (value != null)
				return value.ToString();

			return "";
		}
	}


	public class DALQueryBuilder
	{
		ArrayList fields = new ArrayList();
		string tableName;
		QueryType queryType = QueryType.Insert;
		string clause;

		public DALQueryBuilder(string tableName)
		{
			this.tableName = tableName;
		}

		public DALQueryBuilder(string tableName, string clause)
		{
			queryType = QueryType.Update;
			this.tableName = tableName;
			this.clause = clause;
		}

		public bool IsInserting
		{
			get { return queryType == QueryType.Insert; }
		}

		public void Add(string field, object value)
		{
			QueryItem item;
			item.value = value;
			item.name = field;

			fields.Add(item);
		}


		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();

			if (IsInserting)
			{
				sb.Append("INSERT INTO ");
				sb.Append(tableName);
				sb.Append(" (");

				StringBuilder sbFields = new StringBuilder();
				StringBuilder sbValues = new StringBuilder();

				foreach (QueryItem item in fields)
				{
					sbFields.Append("[");
					sbFields.Append(item.name);
					sbFields.Append("], ");

					if (item.value.GetType() == typeof(string) || item.value.GetType() == typeof(char) ||
					    item.value.GetType() == typeof(DateTime))
					{
						sbValues.Append("'");
						sbValues.Append(item.GetSafeValue());
						sbValues.Append("', ");
					}
					else
					{
						sbValues.Append(item.GetSafeValue());
						sbValues.Append(", ");
					}
				}

				sbFields.Remove(sbFields.Length - 2, 2);
				sbValues.Remove(sbValues.Length - 2, 2);

				sb.Append(sbFields.ToString());

				sb.Append(") VALUES (");
				sb.Append(sbValues.ToString());
				sb.Append(")");
			}
			else
			{
				sb.Append("UPDATE ");
				sb.Append(tableName);
				sb.Append(" SET ");

				foreach (QueryItem item in fields)
				{
					sb.Append("[");
					sb.Append(item.name);
					sb.Append("] = ");

					if (item.value.GetType() == typeof(string) || item.value.GetType() == typeof(char) ||
					    item.value.GetType() == typeof(DateTime))
					{
						sb.Append("'");
						sb.Append(item.GetSafeValue());
						sb.Append("', ");
					}
					else
					{
						sb.Append(item.GetSafeValue());
						sb.Append(", ");
					}
				}

				sb.Remove(sb.Length - 2, 2);
				sb.Append(" WHERE " + clause);
			}			


			return sb.ToString();
		}
	}
}